/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.lookup;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import main.Office;
import main.ServicesList;
import utility.Constants;
import utility.NameValueList;

/**
 *
 * @author jay
 */
public class LookupSimpleFrm extends javax.swing.JDialog {

    private int lookupId;
    private LookupSimpleTM tableModel;
    private List<Object> objects;
    private Object object;
    private Map<NameValueList, Object> filter = new HashMap<>(); 
    
    public LookupSimpleFrm() {
        super(Office.getFrame(), true);
        initComponents();
        initComponentsRules();
    }

    public Object execute(int id, String param) {
        setLocationRelativeTo(null);
        this.lookupId = id;
        txtFilter.setText(param);
        loadData(); 

        setVisible(true);
        return object;
    }
    
    //contoh untuk mencari itemSupplier berdasarkan itemId
    //params.put("supplierName", "namanya apa");  
    //params.put("itemId", 1);  
    public Object execute(int id, Map<NameValueList, Object> params) {
      
        setLocationRelativeTo(null);
        this.lookupId = id;
        this.filter = params;
        
        loadData(); 
        setVisible(true);
        return object;
    }
    
    private void loadData() {
        String params = "", order = "order by nama";
        if (!txtFilter.getText().isEmpty()) {
            params = " where (lower(nama) like lower('%".concat(txtFilter.getText()).concat("%'))");
        }

        switch (lookupId) {
            case Constants.LOOKUP_DEPT: objects = (List) ServicesList.getDeptService().getDept(0, 20, params, order); break;
            case Constants.LOOKUP_UNIT: objects = (List) ServicesList.getUnitService().getUnit(0, 20, params, order); break;    
            case Constants.LOOKUP_PACKAGE: objects = (List) ServicesList.getPackagingService().getPackaging(0, 20, params, order); break;    
            case Constants.LOOKUP_PRINCIPAL: objects = (List) ServicesList.getPrincipalService().getPrincipal(0, 20, params, order); break;    
            case Constants.LOOKUP_SUPPLIER: objects = (List) ServicesList.getSupplierService().getAll(0, 20, params, order); break;    
            case Constants.LOOKUP_ITEM: 
                
                Map<NameValueList, Object> param = new HashMap<>();
                if(!"".equals(txtFilter.getText())) { 
                param.put(new NameValueList("item.nama", Constants.OPERATOR_LIKE), "%"+txtFilter.getText()+"%"); }
                param.put(new NameValueList(null, Constants.OPERATOR_ORDERBY), "item.nama"); 
                objects = (List) ServicesList.getItemService().getItem(0, 20, param); break;    
                
            case Constants.LOOKUP_MAIN_SUPPLIER: 
                filter.remove(new NameValueList("supplier.nama", Constants.OPERATOR_LIKE));
                if (!txtFilter.getText().isEmpty()) {
                    filter.put(new NameValueList("supplier.nama", Constants.OPERATOR_LIKE), txtFilter.getText());
                } 
               
                objects = (List) ServicesList.getItemSupplierService().getAll(0, 20, filter); 
                break;    

            case Constants.LOOKUP_PO: 
                filter.clear();
                if (!txtFilter.getText().isEmpty()) {
                    filter.put(new NameValueList(null, Constants.OPERATOR_ORDERBY), "mst.transNum");
                } 
                filter.put(new NameValueList("mst.statusId", Constants.OPERATOR_EQUAL), Constants.STATUS_TRANS_POSTED); 
                filter.put(new NameValueList(null, Constants.OPERATOR_ORDERBY), "mst.transDate");
                
                objects = (List) ServicesList.getOrderService().getAll(0, 20, filter); 
                
                break;    
                    
            
            default: objects=null; break;    
        }
        
        tableModel = new LookupSimpleTM(lookupId);
        tableModel.clear();
        tableModel.add(objects);
        grid.setModel(tableModel);
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtFilter = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtFilter.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtFilter.setName("txtFilter"); // NOI18N

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        grid.setName("grid"); // NOI18N
        grid.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                gridMouseClicked(evt);
            }
        });
        grid.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                gridKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(grid);

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtFilter, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnOK))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
       if(object!=null){
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Pilih satu terlebih dahulu!",
                    "error",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnOKActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        object=null;
        dispose();        
    }//GEN-LAST:event_btnCancelActionPerformed

    private void gridKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gridKeyPressed
        dispose();
    }//GEN-LAST:event_gridKeyPressed

    private void gridMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gridMouseClicked
        if (evt.getClickCount()==2) { dispose();}
    }//GEN-LAST:event_gridMouseClicked

    @Override
    public void setVisible(boolean value) {
        super.setVisible(value);
        txtFilter.requestFocusInWindow();
    }
        
    class lookupPerformed implements ActionListener {
        @Override public void actionPerformed(ActionEvent e) {
            loadData();
        }
    }
    
    private class LookupSelectionListener implements ListSelectionListener{
        @Override public void valueChanged(ListSelectionEvent e) {
            if(grid.getSelectedRow()>=0){ object = objects.get(grid.getSelectedRow()); }
        }
    }

//    class ActionKeyListener implements KeyListener {
//        @Override public void keyTyped(KeyEvent e) {} 
//        @Override public void keyReleased(KeyEvent e) {}
//        @Override public void keyPressed(KeyEvent e) {
//            switch (e.getKeyCode()) { 
//                               
//                case KeyEvent.VK_ENTER: 
//                    switch(e.getComponent().getName()) {
//                        case "txtFilter": loadData(); break;
//                        case "grid": dispose();break;
//                       default: ; break;
//                    };
//                
//                case KeyEvent.VK_KP_DOWN: 
//                    switch(e.getComponent().getName()) {
//                        case "txtFilter": 
//                            grid.requestFocus(); 
//                            grid.setRowSelectionInterval(1, 1);
//                            break;
////                        case "grid": 
////                            //if(grid.getSelectedRow()==0) {
////                              //  txtFilter.requestFocus();
////                                //txtFilter.setSelectionEnd(lookupId);
////                            //}
////                            break;
//                       default: ; break;
//                    };
//                    
//                break;      
//            }
//        }
//    }
        
    private void initComponentsRules() {
        btnOK.registerKeyboardAction(btnOK.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnOK.registerKeyboardAction(btnOK.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnCancel.registerKeyboardAction(btnCancel.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        btnCancel.registerKeyboardAction(btnCancel.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        txtFilter.addActionListener(new lookupPerformed());
        grid.getSelectionModel().addListSelectionListener(new LookupSelectionListener());
        grid.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        
//        txtFilter.addKeyListener(new ActionKeyListener());
//        grid.addKeyListener(new ActionKeyListener());
    }   
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JTable grid;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtFilter;
    // End of variables declaration//GEN-END:variables
}
